package com.changhong.wlyspectrum.MainTestActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.changhong.wlyspectrum.R;

import com.changhong.wlyspectrum.utils.Bluetooth;
import com.changhong.wlyspectrum.utils.ConnectDialog;
import com.changhong.wlyspectrum.utils.MyConfig;
import com.changhong.wlyspectrum.utils.MyImageTextButton;
import com.changhong.wlyspectrum.utils.MyImageTextButton2;



import android.content.pm.PackageManager;


import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Iterator;
import java.util.UUID;
import android.annotation.SuppressLint;

/**
 * Created by Mr_tao
 * on 2017/3/9.
 */
@SuppressLint("NewApi")
public class MainTestActivity extends Activity{
    private final static String TAG = "MainTestActivity";
    private ImageView mBackIv;
    private TextView mTimeTv;
    private TextView mTitleTv;
    private MyImageTextButton2 mUserBtn;
    private Button mAlcoholBtn;
    private Button mScanBtn;
    private Button mAdjustBtn;


    private HashMap<String, UsbDevice> deviceList;
    private UsbManager manager;
    private UsbDevice mUsbDevice;
    private UsbInterface mInterface;
    private UsbDeviceConnection mDeviceConnection;
    private UsbEndpoint usbEpOut;
    private UsbEndpoint usbEpIn;
    private byte[] receiveytes;
    private PendingIntent mPermissionIntent;
    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    private static final String ACTION_USB_DEVICE_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
    private static final String ACTION_USB_DEVICE_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";

    public static final String ACTION_DISCOVERY_STARTED = "android.bluetooth.adapter.action.DISCOVERY_STARTED";
    public static final String ACTION_DISCOVERY_FINISHED = "android.bluetooth.adapter.action.DISCOVERY_FINISHED";
    private static final String DEVICE_NAME = "BLE1010C2P";
    private static final int ADJUST_DATA = 0;
    private static final int ANALYSIS_DATA = 1;

    private BluetoothReceiver receiver;
    private List<String> devices;

    private ListView bluetoothlist;
    private String[] options;
    private  AlertDialog.Builder mbuilder;
    private  AlertDialog malertDialog;
    private ListView ml;
    private ArrayAdapter<String> adapter;
    private boolean first = false;

    private Bluetooth bluetooth;
    private Boolean isConnect= false;
    private BluetoothGatt mBluetoothGatt;
    private String uuidservice =     "0000b350-d6d8-c7ec-bdf0-eab1bfc6bcbc";
    private String uuidchara_read =  "0000b351-d6d8-c7ec-bdf0-eab1bfc6bcbc";   //read
    private String uuidchara_write = "0000b352-d6d8-c7ec-bdf0-eab1bfc6bcbc";  //write
    private BluetoothGattService service;
    private BluetoothGattCharacteristic characteristic_read;
    private BluetoothGattCharacteristic characteristic_write;
    private BluetoothAdapter mAdapter;
    private int numData = 0;
    private int bluemode;
    private boolean buleadjust_light = false;
    private BluetoothDevice mBluetoothDevice = null;
    private Handler mHandler;
    // 10秒后停止查找搜索.
    private static final long SCAN_PERIOD = 10000;
    private BluetoothAdapter mBluetoothAdapter;

    private String user_id;
    private String collectionId;
    private String title_name;
    private String btn_1_name;
    private String btn_2_name;
    private boolean flag = false;
    private int CountTimes = 0;
    public static double[][] Data = new double[100][2];
    public static double[][] Data1 = new double[100][2];
    public static double[][] Data2 = new double[100][2];
    public static double[][] mData1 = new double[100][2];    //lighton
    public static boolean IsAdjusted = false;
    private  double tem = 0;
    private  double pressure = 0;
    //private  AlertDialog.Builder ad;
    private MyDialog mydialog;
    private Context mcontext;

    private boolean bluetooth_or_usb = true;  //bluetooth:true; usb:false;

    private Boolean istoTRActivity = false;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maintest_layout);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar_maintest_layout);
        manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler());
        mcontext = this;

        InitData();
        InitUi();
        mydialog = new MyDialog(this,1,null);
        mydialog.setCancelable(false);
        mydialog.show();
    }

    private void InitData(){
        Intent intent = getIntent();
        collectionId = intent.getStringExtra("collectionId");
        title_name = intent.getStringExtra("title_name");
        btn_1_name = intent.getStringExtra("btn_1");
        btn_2_name = intent.getStringExtra("btn_2");
        Log.e(TAG,"collectionId----->" + collectionId);
    }
    private void InitUi() {
        mTitleTv = (TextView)findViewById(R.id.title_wuliangye);
        mTitleTv.setText(title_name);

        mBackIv = (ImageView) findViewById(R.id.wuliangye2alcohol);
        mBackIv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

       // mTimeTv = (TextView) findViewById(R.id.tv_time_show);
        //mTimeTv.setText(MyConfig.gettime());

        SharedPreferences mypref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        user_id = mypref.getString("user_id", "");
       /* mUserBtn = (MyImageTextButton2) findViewById(R.id.user_btn);
        mUserBtn.setImgResource(R.drawable.username);
        mUserBtn.setText(getString(R.string.now_user) + user_id);
        mUserBtn.setTextSize(16);
        mUserBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Toast.makeText(getApplicationContext(), "获取用户信息",
                // Toast.LENGTH_SHORT).show();
            }
        });*/

        mAlcoholBtn = (Button) findViewById(R.id.alcohol_btn);
        mAlcoholBtn.setText(btn_1_name);
        mAlcoholBtn.setTextSize(18);
        mAlcoholBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {       //分析
                if(bluetooth_or_usb){
                    bluemode = ANALYSIS_DATA;
                    if(!flag ){
                        MyHandler.sendMessage(Message.obtain(MyHandler, 5));
                    }else{
                        if(istoTRActivity){   //判断是否进入过TestResultActivity，因为断开连接过，需重新连接
                            istoTRActivity = false;
                            mBluetoothGatt = mBluetoothDevice.connectGatt(MainTestActivity.this, false, mGattCallback);
                        }else{
                            ConnectDialog.showDialog(MainTestActivity.this,getString(R.string.scaning));
                            Log.e("wydong","wydong fenxi");
                            writeOrder(MyConfig.blueReadTemp());
                            Delay(300);
                            writeOrder(MyConfig.blueLightOn());
                            Delay(500);
                            writeOrder(MyConfig.blueSetDetect());
                            Delay(500);
                           //writeOrder(MyConfig.blueReadTemp());
                            //Delay(500);
                            //writeOrder(MyConfig.blueReadPressure());
                            //Delay(500);
                        }
                    }
                }else{
                    if(!flag ){
                        MyHandler.sendMessage(Message.obtain(MyHandler, 5));
                    }else{
                        boolean ableusb = InitUsb();
                        if(ableusb){
                            ConnectDialog.showDialog(MainTestActivity.this,getString(R.string.scaning));
                            tem = readTemperture(MyConfig.ReadTemp(), MyConfig.ReadTemp().length);
                            Delay(30);
                            pressure = readPressure(MyConfig.ReadPressure(),MyConfig.ReadTemp().length);
                            Intent mIntent1 = new Intent(ACTION_USB_PERMISSION);
                            mIntent1.putExtra("mode",ANALYSIS_DATA);
                            mPermissionIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mIntent1, PendingIntent.FLAG_UPDATE_CURRENT);
                            manager.requestPermission(mUsbDevice, mPermissionIntent);
                        }else{
                            MyHandler.sendMessage(Message.obtain(MyHandler, 3));
                        };
                    }
                }


            }
        });

        mScanBtn = (Button) findViewById(R.id.scan_btn);
        mScanBtn.setText(btn_2_name);
        mScanBtn.setTextSize(18);
        mScanBtn.setOnClickListener(new View.OnClickListener() {      //样本建模
            @Override
            public void onClick(View v) {
                if(!flag ){
                    MyHandler.sendMessage(Message.obtain(MyHandler, 5));
                }else {
                    if (bluetooth_or_usb) {
                        MyConfig.setDevice(mBluetoothDevice); //画图校准用
                        mBluetoothGatt.disconnect();
                        mBluetoothGatt.close();
                        istoTRActivity = true;
                   /* MyConfig.mBluetoothGatt = mBluetoothGatt;
                    MyConfig.characteristic_read = characteristic_read;
                    MyConfig.characteristic_write = characteristic_write;*/

                    }
                    Intent intent = new Intent(MainTestActivity.this, TestDataActivity.class);
                    intent.putExtra("collectionId", collectionId);
                    startActivity(intent);
                }
            }
        });

        mAdjustBtn = (Button)findViewById(R.id.correct_btn);
        mAdjustBtn.setText(getString(R.string.common_adjust));
        mAdjustBtn.setTextSize(18);
        mAdjustBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(bluetooth_or_usb){
                    bluemode = ADJUST_DATA;
                    if(mBluetoothDevice==null){
                        InitBluetooth();
                    }else{
                        if(istoTRActivity){   //判断是否进入过TestResultActivity，因为断开连接过，需重新连接
                            istoTRActivity = false;
                            mBluetoothGatt = mBluetoothDevice.connectGatt(MainTestActivity.this, false, mGattCallback);
                        }else{
                            MyHandler.sendMessage(Message.obtain(MyHandler, 100));  //已经连接校准过，直接校准
                        }

                    }

                }else{
                    boolean ableusb = InitUsb();
                    Log.e(TAG, "Button Onclick ableusb："+ ableusb);
                    if(ableusb){
                        ConnectDialog.showDialog(MainTestActivity.this,getString(R.string.adjusting));
                        Intent mIntent = new Intent(ACTION_USB_PERMISSION);
                        mIntent.putExtra("mode",ADJUST_DATA);
                        mPermissionIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                        manager.requestPermission(mUsbDevice, mPermissionIntent);
                    }else{
                        MyHandler.sendMessage(Message.obtain(MyHandler, 3));
                    };
                }
            }
        });
    }

    class MyDialog extends AlertDialog{
        private int num ;
        private String result;
        protected MyDialog(Context context) {
            super(context);
        }
        protected MyDialog(Context context ,int num ,String result) {
            super(context);
            this.num = num;
            this.result = result;
        }
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if(num == 1){     //usb and bluetooth choose dialog
                setContentView(R.layout.my_dialog);
                TextView ch_usb = (TextView)findViewById(R.id.choose_usb);
                TextView ch_blue = (TextView)findViewById(R.id.choose_blue);
                ch_usb.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bluetooth_or_usb = false;
                        MyConfig.setModeStatus(false);
                        dismiss();
                    }
                });
                ch_blue.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bluetooth_or_usb = true;
                        MyConfig.setModeStatus(true);
                        int status = 0;
                        // 检查当前手机是否支持ble 蓝牙,如果不支持status=1
                        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
                            Toast.makeText(getApplicationContext(), "手机是否支持ble",Toast.LENGTH_SHORT).show();
                            status = 1;
                        }
                        BluetoothManager bluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
                        mBluetoothAdapter = bluetoothManager.getAdapter();
                        // 检查设备上是否支持蓝牙
                        if (mBluetoothAdapter == null) {
                            status = 1;
                            Toast.makeText(getApplicationContext(), "设备不支持蓝牙",Toast.LENGTH_SHORT).show();
                        }
                        if(status==0){
                            // 为了确保设备上蓝牙能使用, 如果当前蓝牙设备没启用,弹出对话框向用户要求授予权限来启用
                            if (!mBluetoothAdapter.isEnabled()) {
                                mBluetoothAdapter.enable();
                            }
                        }
                        dismiss();
                    }
                });
            }else if(num==2){     //analyse result dialog
                setContentView(R.layout.analyse_result_dialog);
                TextView result = (TextView)findViewById(R.id.iknow_result);
                TextView iknow_buttton = (TextView)findViewById(R.id.iknow_buttton);
                result.setText(this.result);
                iknow_buttton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dismiss();
                    }
                });
            }


        }

        protected void onStop() {
            Log.d("TAG","+++++++++++++++++++++++++++");
        }
    }
    private void InitBluetooth(){
        /*mAdapter = BluetoothAdapter.getDefaultAdapter();
        if(!mAdapter.isEnabled()){
            mAdapter.enable();
        }

        devices = new ArrayList<String>();
        devices.clear();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(ACTION_DISCOVERY_STARTED);
        filter.addAction(ACTION_DISCOVERY_FINISHED);
        receiver = new BluetoothReceiver();
        registerReceiver(receiver, filter);
        mAdapter.startDiscovery();*/

        devices = new ArrayList<String>();
        devices.clear();
        mHandler = new Handler();
        scanLeDevice(true);
    }

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.e("wydong","wydong 333333");
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    if(devices.size()==0){
                        ConnectDialog.dismiss();
                        Toast.makeText(getApplicationContext(), "没有找到目标蓝牙",Toast.LENGTH_SHORT).show();
                    }
                }
            }, SCAN_PERIOD);

            //mScanning = true;
            Log.e("wydong","wydong 2222");
            ConnectDialog.showDialog(MainTestActivity.this,getString(R.string.findbluetooth));
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            //mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    }

    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String name = device.getName();
                    Log.e("wydong","wydong name:"+name);
                    if(isLock(device)){
                        scanLeDevice(false);
                        devices.add(device.getName());
                        mBluetoothDevice = device;
                        mBluetoothGatt = mBluetoothDevice.connectGatt(MainTestActivity.this, false, mGattCallback); //该函数才是真正的去进行连接
                    }
                    //mLeDeviceListAdapter.addDevice(device);
                    //mLeDeviceListAdapter.notifyDataSetChanged();
                }
            });
        }
    };

    private class BluetoothReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e("wydong","wydong action:"+action);
            if(ACTION_DISCOVERY_STARTED.equals(action)){
                Log.e("wydong","wydong ACTION_DISCOVERY_STARTED");
                //ConnectDialog.showDialog(MainTestActivity.this,getString(R.string.findbluetooth));
            }
            if(ACTION_DISCOVERY_FINISHED.equals(action)){
                Log.e("wydong","wydong ACTION_DISCOVERY_FINISHED");
            }
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.e("wydong","wydong device.getName():"+device.getName());
                String name = device.getName();
                if(isLock(device)){
                    devices.add(device.getName());
                    mBluetoothDevice = device;
                    mBluetoothGatt = mBluetoothDevice.connectGatt(MainTestActivity.this, false, mGattCallback); //该函数才是真正的去进行连接
                    mAdapter.cancelDiscovery();
                }
            }
        }
    }

   private boolean isLock(BluetoothDevice device) {
       if(device!=null && device.getName()!= null){
           boolean isLockName = (device.getName()).equals(DEVICE_NAME);
           boolean isSingleDevice = devices.indexOf(device.getName()) == -1;
           return isLockName && isSingleDevice;
       }else{
           return false;
       }

    }

    /**
     * USB初始化
     */
    private boolean InitUsb() {
        //find device
        if(manager == null){
            return false;
        }

        deviceList = manager.getDeviceList();
        if(deviceList.isEmpty()){
            return false;
        }

        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while (deviceIterator.hasNext()) {
            UsbDevice usb = deviceIterator.next();
            int vendorId = usb.getVendorId();
            int productId = usb.getProductId();
            Log.e("ldm", "vid=" + vendorId + "---pid=" + productId);
            if(productId==22352){
                mUsbDevice = usb;
            }
        }
        if (mUsbDevice == null) {
            ConnectDialog.dismiss();
            return false;
        }
        //find interface
        for (int i = 0; i < mUsbDevice.getInterfaceCount();) {
            UsbInterface usbInterface = mUsbDevice.getInterface(i);
            mInterface = usbInterface;
            break;
        }
        if(mInterface == null){
            return false;
        }
        //find endpoint
        Log.e(TAG, "InitUsb ------："+mInterface.getEndpointCount());
        for (int i = 0; i < mInterface.getEndpointCount(); i++) {
            UsbEndpoint ep = mInterface.getEndpoint(i);
            // look for bulk endpoint
            /*if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                    usbEpOut = ep;
                } else {
                    usbEpIn = ep;
                }
            }*/
            // look for interrupte endpoint
            /*if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT) {
                if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                    usbEpOut = ep;
                }
                if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
                    usbEpIn = ep;
                }
            }*/
        if (mInterface.getEndpoint(1) != null) {
            usbEpOut = mInterface.getEndpoint(1);
        }
        if (mInterface.getEndpoint(0) != null) {
            usbEpIn = mInterface.getEndpoint(0);
        }
        }
        if (usbEpOut != null && usbEpIn != null) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * USB指令发送
     */
    private void Detect(int mode){
        Log.e(TAG, "mode----->" + mode);
        if(mode == ANALYSIS_DATA){     //分析 1
            new Thread(new Runnable() {
                public void run() {
                    if(!readDectFromUsb(MyConfig.SetDetect(), MyConfig.SetDetect().length,Data)){
                        MyHandler.sendMessage(Message.obtain(MyHandler, 2));
                    }
                }
            }).start();
        }else if(mode == ADJUST_DATA){   //校准
            Log.e("wydong","wydong usb adjust");
            new Thread(new Runnable() {
                public void run() {
                    boolean flag1 = false;
                    boolean flag4 = false;
                    boolean od3 = sendOrder(MyConfig.SetFlash1(), MyConfig.SetFlash1().length);
                    Delay(300);
                    boolean od4 = sendOrder(MyConfig.LightOn(), MyConfig.LightOn().length);
                    Delay(300);
                    boolean od5 =  sendOrder(MyConfig.SetDetect(), MyConfig.SetDetect().length);
                    Delay(300);
                    flag1 = od3&& od4 && od5;
                    if(flag1){
                        flag4 = rendFromUsb(MyConfig.ReadFlash1(), MyConfig.ReadFlash1().length,mData1);
                    }
                    Log.e(TAG,"flag4:"+flag4);
                    if(flag4){
                        MyHandler.sendMessage(Message.obtain(MyHandler, 0));
                    }else{
                        MyHandler.sendMessage(Message.obtain(MyHandler, 4));
                    }

                }
            }).start();
        }
    }

    /**
     * 读取检测值
     * @param buffer
     * @param length
     */
    private boolean readDectFromUsb(byte[] buffer, int length,double[][] Data) {
        boolean flag = false;
        if (mDeviceConnection != null) {
            try{
                if (mDeviceConnection.bulkTransfer(usbEpOut, buffer, length, 5000)>0) {
                    int num = 0;
                    while (true) {
                        receiveytes = new byte[usbEpIn.getMaxPacketSize()]; // 根据设备实际情况写数据大小
                        int len = mDeviceConnection.bulkTransfer(usbEpIn, receiveytes, receiveytes.length, 2000);
                        //Log.e(TAG, "receive len----->" + len);
                        if (len > 0) {
                            Log.e(TAG, "receive" + "[" + num + "]" +len);
                            /*for (int i = 0; i < len; i++) {
                                Log.e(TAG, "receve" + i + ":0x" + String.format("%2x", receiveytes[i]).toUpperCase());
                            }*/
                            int[] data = {byteToint1(receiveytes[9], receiveytes[8]),
                                    byteToint1(receiveytes[5], receiveytes[4])};
                            Data[num][0] = data[0];
                            Data[num][1] = data[1];
                            num++;
                        } else {
                            break;
                        }
                    }
                    Log.e("wydong","wydong num:"+num);
                    if(num==100){   // 必须获取100个数就算完成
                        flag = true;
                        MyHandler.sendMessage(Message.obtain(MyHandler, 1));

                    }
                }

            }catch (Exception e){
                return false;
            }
        }
        return  flag;
    }

    /**
     * 发送指令
     * @param buffer
     * @param length
     */
    private boolean sendOrder(byte[] buffer, int length){
        try{
            if (mDeviceConnection.bulkTransfer(usbEpOut, buffer, buffer.length, 0) < 0){
                return false;
            }else{
                while (true) {
                    receiveytes = new byte[usbEpIn.getMaxPacketSize()]; // 根据设备实际情况写数据大小
                    if (mDeviceConnection.bulkTransfer(usbEpIn, receiveytes, receiveytes.length, 2000)<0) {
                        break;
                    }
                }
                return true;
            }
        }catch (Exception e){
            Log.e(TAG,"e:"+e);
            return false;
        }

    }


    /**
     * 读取flash里面的值
     * @param buffer
     * @param length
     */
    private boolean rendFromUsb(byte[] buffer, int length ,double[][] mdata){
        boolean flag = false;
        try{
            if (mDeviceConnection.bulkTransfer(usbEpOut, buffer, length, 5000)>0) {
                int num = 0;
                while (true) {
                    receiveytes = new byte[usbEpIn.getMaxPacketSize()]; // 根据设备实际情况写数据大小
                    int len = mDeviceConnection.bulkTransfer(usbEpIn, receiveytes, receiveytes.length, 2000);
                    Log.e(TAG, "receive" + "[" + num + "]" + len);
                    if (len<0) {
                        break;
                    }else if(len>4){
                        /*for (int i = 0; i < len; i++) {
                            Log.e(TAG, "receve" + i + ":0x" + String.format("%2x", receiveytes[i]).toUpperCase());
                        }*/
                        int[] data = { byteToint1(receiveytes[7], receiveytes[6]),
                                byteToint1(receiveytes[5], receiveytes[4]) };
                        mdata[num][0] = data[0];      //光谱波长值 1550-1850
                        mdata[num][1] = data[1];      //对于应得值
                        num++;
                    }
                }
                if(num==100){  //必须获取100个数才算完成
                    flag = true;
                }
            }
            return flag;
        }catch (Exception e){
            Log.e(TAG,"e:"+e);
            return false;
        }
        }


    /**
     * 读取传感器温度值
     */

    private double readTemperture(byte[] buffer, int length){
        if (mDeviceConnection != null) {
            int ret = -1;
            ret = mDeviceConnection.bulkTransfer(usbEpOut, buffer, length, 5000);
            if (ret != -1) {
                int mtemp = 0;
                while (true) {
                    receiveytes = new byte[usbEpIn.getMaxPacketSize()]; // 根据设备实际情况写数据大小
                    ret = mDeviceConnection.bulkTransfer(usbEpIn, receiveytes, receiveytes.length, 1500);
                    if (ret == -1) {
                        break;
                    }
                    mtemp = byteToint1(receiveytes[5], receiveytes[4]);
                }
                return MyConfig.getTemputer(mtemp);
            }else{
                return  0;
            }
        } else {
            return  0;
        }
    }

    private double readPressure(byte[] buffer, int length){
        if (mDeviceConnection != null) {
            int ret = -1;
            ret = mDeviceConnection.bulkTransfer(usbEpOut, buffer, length, 5000);
            if (ret != -1) {
                int mpressure = 0;
                while (true) {
                    receiveytes = new byte[usbEpIn.getMaxPacketSize()]; // 根据设备实际情况写数据大小
                    ret = mDeviceConnection.bulkTransfer(usbEpIn, receiveytes, receiveytes.length, 1500);
                    if (ret == -1) {
                        break;
                    }
                    mpressure = receiveytes[0];
                }
                return mpressure;
            }else{
                return  0;
            }
        } else {
            return  0;
        }
    }


    /**
     * 延时函数
     * @param time
     */
    private void Delay(int time){
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 数据转换
     * @param hbyte 高位数据
     * @param lbyte 低位数据
     * @return
     */
    private int byteToint1(byte hbyte, byte lbyte) {
        int l = lbyte;
        l &= 0xFF;
        l |= ((int) hbyte << 8);
        l &= 0xFFFF;
        return l;
    }

    private Handler MyHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            ConnectDialog.dismiss();
            switch (msg.what) {
                case 0:
                    IsAdjusted = true;
                    flag = true;
                    MyConfig.bubbleSort(mData1);
                    //七点平滑
                    MyConfig.Smoothing(mData1);
                    MyConfig.showTmsg(getApplicationContext(),getString(R.string.finish_calibration));
                    break;
                case 1:
                    MyConfig.bubbleSort(Data); //排序
                    MyConfig.Smoothing(Data);  //平滑

                    //获得最大值
                    double max = 0;
                    for(int i = 0;i<Data.length;i++){
                        if(Data[i][1]>=max){
                            max = Data[i][1];
                        }
                    }
                    //
                    if(collectionId.equals("10")){   //纺织品样本，11805 -11815
                        int index = 0;
                        double min = Data[0][1]/max;
                        for(int i=0;i<Data.length;i++){
                            if(min>Data[i][1]/max){
                                min = Data[i][1]/max;
                                index = i;
                            }
                        }
                        if(index>37 && index <43){    //波谷索引40处，判断为仿真丝和牛津布
                            if(min>0.9723){    //为仿真丝
                                showResultDialog(getString(R.string.Silk));
                            }else{   //牛津布
                                showResultDialog(getString(R.string.Oxford_cloth));
                            }
                        }else{
                            if(Data[33][1]/max <0.975){   //光谱1650处，为牛仔布
                                showResultDialog(getString(R.string.denim));
                            }else{
                                int index1 = 33;
                                double min1 = Data[33][1]/max;
                                for(int i=33;i<67;i++){    //1650到1750波段
                                    if(min1>Data[i][1]/max){
                                        min1 = Data[i][1]/max;
                                        index1 = i;
                                    }
                                }
                                if(index1<35){//最小处索引基本上为33处时，为棉麻和纯棉汗布
                                    if(Data[0][1]/max <0.9706){ //  纯棉汗布
                                        showResultDialog(getString(R.string.Cotton_jersey));
                                    }else{                      //棉麻
                                        showResultDialog(getString(R.string.Linen));
                                    }
                                }else{       //否则为真丝、法兰绒、罗马布
                                    if(index1>52){  //罗马布
                                        showResultDialog(getString(R.string.Roman_cloth));
                                    }else{
                                        if(Data[0][1]/max<0.977){   //真丝缎面
                                            showResultDialog(getString(R.string.Silk_satin_face));
                                        }else{              //法兰绒
                                            showResultDialog(getString(R.string.Flannel));
                                        }
                                    }
                                }
                            }
                        }
                       /* double md = Data[0][1]/max;  //取1150第一个数
                        if(md>0.9762){
                            if(md<0.9804){
                                showResultDialog(getString(R.string.Roman_cloth));
                            }else{
                                showResultDialog(getString(R.string.Flannel));
                            }
                        }else{
                            if(md>0.9715){
                                showResultDialog(getString(R.string.Silk_satin_face));
                            }else{
                                showResultDialog(getString(R.string.Cotton_jersey));
                            }
                        }*/
                    }else  if(collectionId.equals("44")){    //塑料颗粒 11825-11829
                        double md = Data[30][1]/max;
                        if(md>0.960){   //索引30 即1640处比较 ，大者为 pp
                            showResultDialog("pp");
                        }else{
                            if(Data[99][1]/max>0.9579){     //1850处比较 ，大者为 pmma
                                showResultDialog("pmma");
                            }else {
                                if(Data[22][1]/max>0.9621){    //索引22 即1616处比较 ，大者为 abs
                                    showResultDialog("abs");
                                }else{
                                    if(Data[99][1]/max>0.9481){
                                        showResultDialog("as");
                                    }else{
                                        showResultDialog("gbps");
                                    }
                                }
                               /* if(Data[99][1]/max>0.961){
                                    showResultDialog("pc");
                                }else{
                                    int index = 0;
                                    double min = Data[0][1]/max;
                                    for(int i=0;i<Data.length;i++){
                                        if(min>Data[i][1]/max){
                                            min = Data[i][1]/max;
                                            index = i;
                                        }
                                    }
                                    if(index<=43){    //波谷位置索引41 、42、 43
                                        showResultDialog("pmma");
                                    }else {
                                        if(Data[99][1]>0.957){
                                            showResultDialog("abs");
                                        }else{
                                            showResultDialog("gbps");
                                        }
                                    }
                                }*/
                            }

                                /*
                            if(Data[99][1]/max>0.9562 && Data[99][1]/max<0.9630){
                                showResultDialog("abs");
                            }else{
                                if(Data[17][1]/max>0.968){
                                    showResultDialog("pmma");
                                }else{
                                    if(Data[99][1]/max>0.961){
                                        showResultDialog("pc");
                                    }else{
                                        if((Data[99][1]-Data[41][1])/max>0.121){
                                            showResultDialog("as");
                                        }else{
                                            showResultDialog("gbps");
                                        }
                                    }
                                }
                            }*/
                        }
                    }else{
                        double[] mseries = new double[100];
                        double[] mnoLightSeries = new double[100];
                        double[] mbaseLightSeries = new double[100];
                        for(int i = 0;i < Data.length;i++){
                            mseries[i] = Data[i][1];
                            mbaseLightSeries[i]	= mData1[i][1];
                        }
                        MyConfig.predictRequest.setId(user_id);
                        MyConfig.predictRequest.setSeries(mseries);
                        MyConfig.predictRequest.setBaseLightSeries(mbaseLightSeries);

                        CountTimes = 0;
                        Intent intent = new Intent(MainTestActivity.this, TestAnalyseActivity.class);
                        Toast.makeText(getApplicationContext(),"温度是："+tem+",电池电压："+pressure, Toast.LENGTH_LONG).show();
                        intent.putExtra("collectionId",collectionId);
                        intent.putExtra("temperture",tem);
                        startActivity(intent);
                    }
                    break;
                case 2:
                    Toast.makeText(getApplicationContext(), "数据传输错误，请重新检测", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    MyConfig.showTmsg(getApplicationContext(),getString(R.string.device_not_found));
                    break;
                case 4:
                    MyConfig.showTmsg(getApplicationContext(),getString(R.string.device_connect_abnormal));
                    break;
                case 5:
                    MyConfig.showTmsg(getApplicationContext(),getString(R.string.adjust_first));
                    break;
                case 6:
                    MyConfig.showTmsg(getApplicationContext(),getString(R.string.erro_connecte));
                    break;
                case 7:
                    MyConfig.showTmsg(getApplicationContext(),getString(R.string.no_permission));
                    break;
                case 8:
                    MyConfig.showTmsg(getApplicationContext(),getString(R.string.device_connectedd));
                    break;
                case 9:
                    MyConfig.showTmsg(getApplicationContext(),getString(R.string.device_disconnect));
                    break;

                case 100:  //connect sucessful  and light off
                    ConnectDialog.showDialog(MainTestActivity.this,getString(R.string.adjusting));
                    //isConnect = true;
                    service = mBluetoothGatt.getService(UUID.fromString(uuidservice));
                    characteristic_read= service.getCharacteristic(UUID.fromString(uuidchara_read));
                    characteristic_write = service.getCharacteristic(UUID.fromString(uuidchara_write));

                    //将指令放置进特征中
                    writeOrder(MyConfig.blueSetFlash1());
                    Delay(500);
                    writeOrder(MyConfig.blueLightOn());
                    Delay(500);
                    writeOrder(MyConfig.blueSetDetect());
                    Delay(500);
                    break;

                default:
                    break;
            }
        }
    };

    private void showResultDialog(String mstring){
        MyDialog mdialog = new MyDialog(mcontext,2,mstring);
        mdialog.setCancelable(false);
        mdialog.show();
    }

    private  void writeOrder(final byte[] bytes){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    characteristic_write.setValue(bytes);
                    //设置回复形式
                    characteristic_write.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
                    //开始写数据
                    mBluetoothGatt.writeCharacteristic(characteristic_write);
                    mBluetoothGatt.setCharacteristicNotification(characteristic_read,true);
                } catch (Exception e) {
                    Log.e("Write", e.toString());
                }
            }
        });
        thread.start();

    }
    /**
     * 异常捕获
     */
    public class CustomExceptionHandler implements Thread.UncaughtExceptionHandler {

        private Thread.UncaughtExceptionHandler mDefaultUEH;

        public CustomExceptionHandler() {
            Log.d(TAG, "------------ CustomExceptionHandler ------------");
            mDefaultUEH = Thread.getDefaultUncaughtExceptionHandler();
        }

        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            Log.e(TAG, "------------ uncaughtException ------------ " + ex.getMessage());

            mDefaultUEH.uncaughtException(thread, ex); // 不加本语句会导致ANR
        }

    }

    /**
     * 注册USB权限等广播
     */
    BroadcastReceiver mReceiver1 = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, action);
            if (action.equals(ACTION_USB_PERMISSION)) {
                synchronized (this) {
                    Integer mode = intent.getIntExtra("mode",-1);
                        if (mInterface != null) {
                            UsbDeviceConnection conn = null;
                            if (manager.hasPermission(mUsbDevice)) {
                                conn = manager.openDevice(mUsbDevice);
                                if (conn == null) {
                                    return;
                                }
                                if (conn.claimInterface(mInterface, true)) {
                                    mDeviceConnection = conn;
                                    Detect(mode);
                                } else {
                                    MyHandler.sendMessage(Message.obtain(MyHandler, 6));
                                    conn.close();
                                }
                            } else {
                                ConnectDialog.dismiss();
                                MyHandler.sendMessage(Message.obtain(MyHandler, 7));

                            }
                        }
                }
            } else if (action.equals(ACTION_USB_DEVICE_ATTACHED)) {
                MyHandler.sendMessage(Message.obtain(MyHandler, 8));

            } else if (action.equals(ACTION_USB_DEVICE_DETACHED)) {
                ConnectDialog.dismiss();
                MyHandler.sendMessage(Message.obtain(MyHandler, 9));
            }
        }

    };

    @Override
    protected void onDestroy() {
        Log.e(TAG, "OnDestroy");
        if(receiver!=null){
            unregisterReceiver(receiver);
        }
        if(mBluetoothGatt!=null){
            mBluetoothGatt.disconnect();
            mBluetoothGatt.close();
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {

        Log.e(TAG, "onPause");
        unregisterReceiver(mReceiver1);
        super.onPause();
    }

    @Override
    protected void onResume() {
        Log.e(TAG, "onResume");
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
        filter.addAction(ACTION_USB_PERMISSION);
        registerReceiver(mReceiver1, filter);
        super.onResume();
    }


    private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

        //连接状态改变的回调
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                            int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // 连接成功后启动服务发现
                Log.e(TAG, "启动服务发现:" + mBluetoothGatt.discoverServices());

            }
        };

        //发现服务的回调
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            ConnectDialog.dismiss();
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.e(TAG, "成功发现服务");
                MyHandler.sendMessage(Message.obtain(MyHandler, 100));
            }else{
                Log.e(TAG, "服务发现失败，错误码为:" + status);
            }
        };

        //写操作的回调
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.e(TAG, "写入成功:" +characteristic.getValue().length);
            }

        };

        //读操作的回调
        public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.e(TAG, "读取成功:" +characteristic.getValue().length);
            }
        }

        //数据返回的回调（此处接收BLE设备返回数据）
        public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {
            Log.e(TAG,"Changed:"+characteristic.getValue().length);
            byte[] receiveytes = characteristic.getValue();

            if(receiveytes.length==12){
                Log.e(TAG,"wydong bluemode:"+bluemode);
                if(bluemode == ADJUST_DATA){   //校准  0
                    int[] data = { byteToint1(receiveytes[9], receiveytes[8]),
                            byteToint1(receiveytes[5], receiveytes[4]) };
                        if(numData<100){
                            mData1[numData][0] = data[0];
                            mData1[numData][1] = data[1];
                            numData+=1;
                        }
                        Log.e(TAG,"Changed on校准numData:"+numData);
                        if(numData==100){
                            MyHandler.sendMessage(Message.obtain(MyHandler, 0));
                            numData = 0;
                        }

                }else{      //分析
                    Log.e(TAG,"Changed 分析....");
                    int[] data = {byteToint1(receiveytes[9], receiveytes[8]),
                            byteToint1(receiveytes[5], receiveytes[4])};
                    if(numData<100){
                        Data[numData][0] = data[0];
                        Data[numData][1] = data[1];
                        numData+=1;
                    }
                    Log.e(TAG,"Changed on分析numData:"+numData);
                    if(numData==100){
                        MyHandler.sendMessage(Message.obtain(MyHandler, 1));
                        numData = 0;
                    }
                }

            }
            if(receiveytes.length==6){   //temputer
                int mtemp = byteToint1(receiveytes[5], receiveytes[4]);
                Log.e(TAG,"Changed mtemp:"+mtemp);
                Log.e("wydong","wydong:"+Math.log(10)+","+Math.log(2.7182));
                tem = MyConfig.getTemputer(mtemp);
                Log.e(TAG,"Changed 温度:"+tem);
            }

            if(receiveytes.length<6){   //pressure
               /* int mpressure = receiveytes[0];
                pressure = mpressure;
                Log.e(TAG,"Changed 电压:"+pressure);*/
               for(int i=0;i<receiveytes.length;i++){
                   Log.e("wydong","wydong receiveytes:"+receiveytes[i]);
               }

            }

        };
    };

}
